package cc.spider.web.util;

import cc.spider.web.model.http.Cookie;

import java.text.ParseException;
import java.util.Locale;

public class CookieUtil {
    public interface AttrNameFormatter {
        String format(String name);
    }

    public static AttrNameFormatter defaultAttrNameFormatter = new AttrNameFormatter() {
        @Override
        public String format(String name) {
            if (name.startsWith("comment")) {
                return "Comment";
            } else if (name.startsWith("version")) {
                return "Version";
            } else {
                return name;
            }
        }
    };

    public static Cookie parseCookie(String header, AttrNameFormatter attrNameFormatter) {
        if (attrNameFormatter == null) {
            attrNameFormatter = defaultAttrNameFormatter;
        }
        String[] bites = header.split("[;,]");
        Cookie cookie = null;
        for (int i = 0; i < bites.length; i++) {
            String[] crumbs = bites[i].split("=", 2);
            String name = crumbs.length > 0 ? crumbs[0].trim() : "";
            String value = crumbs.length > 1 ? crumbs[1].trim() : "";

            if (value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) {
                value = value.substring(1, value.length() - 1);
            }

            if (cookie == null) {
                cookie = new Cookie(name, value);
            } else {
                final String param = name.toLowerCase(Locale.ROOT);
                if (param.startsWith("domain")) {
                    cookie.setDomain(value);
                } else if (param.startsWith("max-age")) {
                    cookie.setMaxAge(Integer.parseInt(value));
                } else if (param.startsWith("path")) {
                    cookie.setPath(value);
                } else if (param.startsWith("secure")) {
                    cookie.setSecure(value.equalsIgnoreCase("true") || value.equals(""));
                } else if (param.startsWith("httponly")) {
                    cookie.setHttpOnly(value.equalsIgnoreCase("true") || value.equals(""));
                } else if (param.startsWith("expires")) {
                    try {
                        cookie.setExpiry(HttpDateFormat.readDate(value + ", " + bites[++i]));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    cookie.addAttr(attrNameFormatter.format(name), value);
                }
            }
        }
        return cookie;
    }

    public static Cookie parseCookie(String header) {
        return parseCookie(header, defaultAttrNameFormatter);
    }
}
